package slxy.jiangtao.dts.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

/** Created by JiangTao on 2016/11/29. */
public final class EntityUtil {
  private static final Logger logger = LoggerFactory.getLogger(EntityUtil.class);

  private EntityUtil() {}

  /**
   * 获取实体表名
   *
   * @param clazz
   * @return
   */
  public static String getTableName(Class clazz) {
    Table tableAnnotation = (Table) clazz.getAnnotation(Table.class);
    return Optional.ofNullable(tableAnnotation).map(Table::name).orElse(null);
  }

  /**
   * 获取实体属性及对应的数据库字段 key: 数据库字段 value: 属性
   *
   * @param clazz
   * @return
   */
  public static Map<String, String> getColumnNames(Class<?> clazz) {
    Map<String, String> returnFields = new HashMap<>();
    // 获取父类的ID字段
    Field[] supperDeclaredFields = clazz.getSuperclass().getDeclaredFields();
    Field[] declaredFields = clazz.getDeclaredFields();
    Stream.of(declaredFields, supperDeclaredFields)
        .forEach(
            fields -> {
              for (Field field : fields) {
                Optional.ofNullable(field.getAnnotation(Column.class))
                    .ifPresent(column -> returnFields.put(column.name(), field.getName()));
              }
            });
    return returnFields;
  }
}
